
from app01 import models
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from app01.utils.bootstrap import BootStrapModelForm


class UserModelForm(BootStrapModelForm):
    name = forms.CharField(min_length=3,
                           label="用户名",
                           widget=forms.TextInput(attrs={'class': 'form-control'})
                           )
    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'account', 'create_time', 'gender', 'depart']

class MobileModelForm(BootStrapModelForm):

    #使用正则表达式，检验号码是否输入合法
    mobile = forms.CharField(
        label = "手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')],
    )
    class Meta:
        model = models.MobileInfo
        ##fields = ["mobile", "price", "level", "status"]
        fields = '__all__'
        # 或则排除那个字段
        # exclude =['lecvel']


    ## 判断手机号是否重复
    def clean_mobile(self):
        txt_mobile = self.cleaned_data['mobile']  # 获取用户提交的手机号
        exists = models.MobileInfo.objects.filter(mobile=txt_mobile).exists()  # 正确调用 exists 方法
        if exists:
            raise ValidationError("手机号已存在")  # 如果手机号已经存在，抛出验证错误
        return txt_mobile

class MobileeditModelForm(forms.ModelForm):
    mobile = forms.CharField(
        label="手机号",
        disabled=True,  # 如果需要完全禁用，可以继续使用 disabled
        widget=forms.TextInput(attrs={'readonly': 'readonly'})  # 添加readonly属性
    )

    class Meta:
        model = models.MobileInfo
        fields = ["mobile","price", "level", "status"]
    # 添加bootstrap样式
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        #循环找到所有的插件，添加class=“”样式
        for name, field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}
